//
//  NSMutableAttributedString+NED.m
//  QNote
//
//  Created by 林宁宁 on 2017/3/12.
//  Copyright © 2017年 林宁宁. All rights reserved.
//

#import "NSMutableAttributedString+NED.h"
#import <CoreText/CTFramesetter.h>

@implementation NSMutableAttributedString (NED)


+(instancetype)ned_initWithStr:(NSString *)str customBlock:(void (^)(NSMutableAttributedString *))customBlock
{
    if(!str)
    {
        str = @"";
    }
    
    NSMutableAttributedString * att = [[NSMutableAttributedString alloc] initWithString:str];
    
    if(customBlock)
    {
        customBlock(att);
    }
    
    return att;
}

-(void)ned_appendStr:(NSString *)str block:(void (^)(NSMutableAttributedString *, NSString *))appendBlock
{
    if(!str)
    {
        str = @"";
    }
    
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc] initWithString:str];
    if(appendBlock)
    {
        appendBlock(attStr,str);
    }
    
    [self appendAttributedString:attStr];    
}

-(void)ned_insertStr:(NSString *)str atIndex:(NSUInteger)loc block:(void (^)(NSMutableAttributedString *, NSString *))insertBlock
{
    if(!str)
    {
        str = @"";
    }
    
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc] initWithString:str];
    if(insertBlock)
    {
        insertBlock(attStr,str);
    }
    
    [self insertAttributedString:attStr atIndex:loc];
}



- (void)ned_font:(UIFont *)font
{
    NSRange range = NSMakeRange(0, [self length]);
    
    [self addAttribute:NSFontAttributeName value:font range:range];
}

- (void)ned_font:(UIFont *)font range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSFontAttributeName value:font range:range];
}





- (void)ned_color:(UIColor *)color
{
    NSRange range = NSMakeRange(0, [self length]);
    
    [self addAttribute:NSForegroundColorAttributeName value:color range:range];
}

- (void)ned_color:(UIColor *)color range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSForegroundColorAttributeName value:color range:range];
}



/**
 设置区域背景颜色
 */
- (void)ned_bgcolor:(UIColor *)color
{
    [self ned_bgcolor:color range:NSMakeRange(0, [self length])];
}

- (void)ned_bgcolor:(UIColor *)color range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    if(color)
    {
        [self addAttribute:NSBackgroundColorAttributeName value:color range:range];
    }
    else
    {
        [self removeAttribute:NSBackgroundColorAttributeName range:range];
    }
}





- (void)ned_baseLineOffset:(float)offset
{
    NSRange range = NSMakeRange(0, [self length]);
    
    [self ned_baseLineOffset:offset range:range];
}

- (void)ned_baseLineOffset:(float)offset range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSBaselineOffsetAttributeName value:@(offset) range:range];
}



/**
 文本字符间隔
 */
- (void)ned_characterSpacing:(NSNumber *)characterSpaceing
{
    NSRange range = NSMakeRange(0, [self length]);
    
    [self ned_characterSpacing:characterSpaceing range:range];
}

- (void)ned_characterSpacing:(NSNumber *)characterSpaceing range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSKernAttributeName value:characterSpaceing range:range];
}





- (void)ned_underlineStyle:(NSUnderlineStyle)style
{
    NSRange range = NSMakeRange(0, [self length]);
    
    [self ned_underlineStyle:style range:range];
}

- (void)ned_underlineStyle:(NSUnderlineStyle)style
                    range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSUnderlineStyleAttributeName value:@(style) range:range];
}


/**
 删除线
 */
- (void)ned_strikethrough:(NSUInteger)value
{
    [self ned_strikethrough:value range:NSMakeRange(0, [self length])];
}

- (void)ned_strikethrough:(NSUInteger)value
                   range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSStrikethroughStyleAttributeName value:@(value) range:range];
    [self addAttribute:NSBaselineOffsetAttributeName value:@(0) range:range];
}


- (void)ned_strikethroughColor:(UIColor *)color
{
    [self ned_strikethroughColor:color range:NSMakeRange(0, [self length])];
}

- (void)ned_strikethroughColor:(UIColor *)color
                        range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSStrikethroughColorAttributeName value:color range:range];
}


/**
 阴影
 */
- (void)ned_shadow:(NSShadow *)shadow
{
    [self ned_shadow:shadow range:NSMakeRange(0, [self length])];
}

- (void)ned_shadow:(NSShadow *)shadow
            range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSShadowAttributeName value:shadow range:range];
}





- (void)ned_Obliqueness:(NSNumber *)value
{
    [self ned_Obliqueness:value range:NSMakeRange(0, [self length])];
}

- (void)ned_Obliqueness:(NSNumber *)value
                 range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSObliquenessAttributeName value:value range:range];
}




- (void)ned_Expansion:(NSNumber *)value
{
    [self ned_Expansion:value range:NSMakeRange(0, [self length])];
}

- (void)ned_Expansion:(NSNumber *)value
               range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSExpansionAttributeName value:value range:range];
}




/**
 下划线的颜色
 */
- (void)ned_underlineColor:(UIColor *)color
{
    NSRange range = NSMakeRange(0, [self length]);
    
    [self ned_underlineColor:color range:range];
}

- (void)ned_underlineColor:(UIColor *)color
                    range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSUnderlineColorAttributeName value:color range:range];
}


- (void)ned_effect
{
    [self ned_effectWithRange:NSMakeRange(0, [self length])];
}

- (void)ned_effectWithRange:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSTextEffectAttributeName value:NSTextEffectLetterpressStyle range:range];
}



/**
 添加链接
 */
- (void)ned_linkURL:(NSURL *)url
{
    [self ned_linkURL:url range:NSMakeRange(0, [self length])];
}

- (void)ned_linkURL:(NSURL *)url
             range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSLinkAttributeName value:url range:range];
}



/**
 字体的描边和颜色
 */
- (void)ned_strokeWidth:(NSNumber *)strokeWidth
{
    [self ned_strokeWidth:strokeWidth range:NSMakeRange(0, [self length])];
}

-(void)ned_strokeWidth:(NSNumber *)strokeWidth range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    [self addAttribute:NSStrokeWidthAttributeName value:strokeWidth range:range];
}


-(void)ned_strokeColor:(UIColor *)strokeColor
{
    [self ned_strokeColor:strokeColor range:NSMakeRange(0, [self length])];
}

-(void)ned_strokeColor:(UIColor *)strokeColor range:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    if(strokeColor)
    {
        [self addAttribute:NSStrokeColorAttributeName value:strokeColor range:range];
    }
    else
    {
        [self removeAttribute:NSStrokeColorAttributeName range:range];
    }
}


//图片
- (void)ned_attachImage:(UIImage *)image
{
    [self ned_attachImage:image imageSize:CGSizeMake(image.size.width, image.size.height)];
}

- (void)ned_attachImage:(UIImage *)image imageSize:(CGSize)imgSize
{
    NSTextAttachment * attach = [[NSTextAttachment alloc] init];
    attach.image = image;
    attach.bounds = CGRectMake(0, 0, imgSize.width, imgSize.height);
    
    NSMutableAttributedString * imageStr = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attach]];
    
//    [imageStr ned_baseLineOffset:-imgSize.height*0.18];
    
    [self appendAttributedString:imageStr];
}


- (void)ned_attachImage:(UIImage *)image imageSize:(CGSize)imgSize atIndex:(NSInteger)index
{
    [self ned_attachImage:image imageSize:imgSize atIndex:index imageOffset:nil];
}

- (void)ned_attachImage:(UIImage *)image imageSize:(CGSize)imgSize atIndex:(NSInteger)index imageOffset:(NSNumber *)offset
{
    if(index > self.string.length)
    {
        return;
    }
    
    CGFloat offY = 0;
    if(offset){
        offY = [offset floatValue];
    }
//    else{
//        offY = -imgSize.height*0.15;
//    }
    
    NSTextAttachment * attach = [[NSTextAttachment alloc] init];
    attach.image = image;
    if(CGSizeEqualToSize(imgSize, CGSizeZero))
    {
        attach.bounds = CGRectMake(0, offY, image.size.width, image.size.height);
    }
    else
    {
        attach.bounds = CGRectMake(0, offY, imgSize.width, imgSize.height);
    }
    
    NSMutableAttributedString * imageStr = [[NSMutableAttributedString alloc] initWithAttributedString:[NSAttributedString attributedStringWithAttachment:attach]];

    [self insertAttributedString:imageStr atIndex:index];
}


- (void)ned_paragraphBlock:(void (^)(NSMutableParagraphStyle *))paragraphBlock
{
    NSRange range = NSMakeRange(0, self.string.length);
    
    [self ned_paragraphBlock:paragraphBlock andRange:range];
}

- (void)ned_paragraphBlock:(void (^)(NSMutableParagraphStyle *))paragraphBlock andRange:(NSRange)range
{
    if(NSMaxRange(range) > [self length])
    {
        return;
    }
    
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    
    if(paragraphBlock)
    {
        paragraphBlock(paragraphStyle);
    }
    
    [self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
}



///**
// 附加文字
// */
//- (void)ned_appendText:(NSString *)text config:(void (^)(NSMutableAttributedString *))customBlock{
//    
//    NSMutableAttributedString * attText = [NSMutableAttributedString ned_initWithStr:text customBlock:customBlock];
//    [self appendAttributedString:attText];
//    
//}

@end


@implementation NSMutableAttributedString (NEDHTML)


+ (instancetype)ned_initHTML:(NSString *)html{
    NSMutableAttributedString * attHTML = [[NSMutableAttributedString alloc] initWithData:[html?:@"" dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];
    [attHTML ned_paragraphBlock:^(NSMutableParagraphStyle *style) {
        style.lineSpacing = 5;
        style.alignment = NSTextAlignmentCenter;
    }];
    return attHTML;
}
- (instancetype)ned_appendHTML:(NSString *)html{
    if(!html){
        return self;
    }
    [self appendAttributedString:[NSMutableAttributedString ned_initHTML:html]];
    return self;
}
- (instancetype)ned_appendHTML:(NSString *)html anIndex:(NSInteger)loc{
    if(!html){
        return self;
    }
    [self insertAttributedString:[NSMutableAttributedString ned_initHTML:html] atIndex:loc];
    return self;
}

- (NSMutableAttributedString *(^)(NSTextAlignment))html_alignment{
    NSMutableAttributedString *(^block)(NSTextAlignment alignment) = ^NSMutableAttributedString *(NSTextAlignment alignment) {
        
        __block BOOL shouldAdd = YES;
        [self enumerateAttribute:NSParagraphStyleAttributeName inRange:NSMakeRange(0, self.string.length) options:(NSAttributedStringEnumerationReverse) usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
            NSMutableParagraphStyle * style;
            if([value isKindOfClass:NSMutableParagraphStyle.class]){
                style = (NSMutableParagraphStyle *)value;
                style.alignment = alignment;
            }else if([value isKindOfClass:NSParagraphStyle.class]){
                style = [[NSMutableParagraphStyle alloc] init];
                [style setParagraphStyle:value];
                style.alignment = alignment;
            }
            if(style){
                shouldAdd = NO;
                [self addAttribute:NSParagraphStyleAttributeName value:style range:range];
            }
        }];
        if(shouldAdd){
            [self ned_paragraphBlock:^(NSMutableParagraphStyle *style) {
                style.alignment = alignment;
            }];
        }
        return self;
    };
    return block;
}

- (NSMutableAttributedString *(^)(UIFont *))html_defaultFont{
    NSMutableAttributedString *(^block)(UIFont * defaultFont) = ^NSMutableAttributedString *(UIFont * defaultFont) {
        NSRange mainRange = NSMakeRange(0, self.string.length);
        [self enumerateAttribute:NSFontAttributeName inRange:mainRange options:NSAttributedStringEnumerationReverse usingBlock:^(UIFont *  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
            if(NSEqualRanges(range, mainRange)){
                [self ned_font:defaultFont];
                *stop = YES;
                return;
            }
            if([value.fontName.lowercaseString hasPrefix:@"times"] && value.pointSize<=12){
                [self ned_font:defaultFont range:range];
            }
        }];
        return self;
    };
    return block;
}
- (NSMutableAttributedString *(^)(UIColor *))html_defaultColor{
    NSMutableAttributedString *(^block)(UIColor * defaultColor) = ^NSMutableAttributedString *(UIColor * defaultColor) {
        NSRange mainRange = NSMakeRange(0, self.string.length);
        [self enumerateAttribute:NSForegroundColorAttributeName inRange:mainRange options:NSAttributedStringEnumerationReverse usingBlock:^(UIColor *  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
            if(NSEqualRanges(range, mainRange)){
                [self ned_color:defaultColor];
                *stop = YES;
                return;
            }
            CGFloat r = 0, g = 0, b = 0, a = 0;
            [value getRed:&r green:&g blue:&b alpha:&a];
            if(r == 0 && g == 0 && b == 0 && a == 1){
                [self ned_color:defaultColor range:range];
            }
        }];
        return self;
    };
    return block;
}


@end


@implementation NSAttributedString (NED)


- (CGSize)ned_getSizeConstrainedToSize:(CGSize)size{
    //有图片的时候高度计算不准确
//    CGSize fitSize = [self boundingRectWithSize:size options:(NSStringDrawingUsesFontLeading |NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesDeviceMetrics) context:NULL].size;
//    return CGSizeMake(ceil(fitSize.width), ceil(fitSize.height));;

    UILabel * tempLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    tempLabel.attributedText = self;
    tempLabel.numberOfLines = 0;
    tempLabel.lineBreakMode = NSLineBreakByWordWrapping;
    [tempLabel sizeToFit];

    CGSize fitSize = tempLabel.frame.size;
    fitSize = CGSizeMake(ceil(fitSize.width), ceil(fitSize.height));
    return fitSize;
    
}


@end
